
#include "worker.h"

void *rp_rpointd_worker(void *arg)
{
	static char fname[] = "rp_rpointd_worker";
	static char msg[] = "fatal error";
	Err err;
	Request *req;
	struct event_base *evb_worker;
	struct event ev_worker;
	FLOG_IN(fname);
	
	evb_worker = event_init();		
	while (1)
	{
		/*	get the next request    */
		err = rp_mutex_lock(&(global.mutex_worker));
		err = rp_sem_wait(&(global.sem_worker));
		req = rp_rpointd_rq_get(&global.rq_client);
		err = rp_mutex_unlock(&(global.mutex_worker));
		if (req == NULL) continue;
		/*	check if we need to exit    */
		if (req->fd == -1)
		{
			rp_log(LOG_DEBUG, fname, "Worker thread exits. TID = %d");
			break;	
		}
		/*	serve the request    */
		event_set(&ev_worker, req->fd, EV_READ|EV_WRITE|EV_PERSIST, rp_rpointd_worker_io, NULL);  
		event_base_set(evb_worker, &ev_worker);		
		if (event_add(&ev_worker, 0) < 0)
		{
			rp_log(LOG_FATAL, fname, msg);
			break;
		}
		event_base_dispatch(evb_worker);	

		close(req->fd);
	}
	free(req);
	
	err = rp_thread_exit();
	FLOG_OUT(fname);
	return NULL;
}

void rp_rpointd_worker_io(int fd, short event, void *arg)
{
	static char fname[] = "rp_rpointd_worker_io";
	static char msg[] = "fatal error";
	static Err err;
	FLOG_IN(fname);
	
	if (event == EV_READ)
	{
		
	} else {	// EV_WRITE

	}
	
	FLOG_OUT(fname);
}

Err rp_rpointd_worker_set_busy(int id)
{
	static char fname[] = "rp_rpointd_worker_set_busy";
	static char msg[] = "fatal error";
	static Err err;

	err = rp_mutex_lock(&((global.status_worker+id)->mutex));
	(global.status_worker+id)->state = SS_BUSY;
	err = rp_mutex_unlock(&((global.status_worker+id)->mutex));

	return err;
}

Err rp_rpointd_worker_set_idle(int id)
{
	static char fname[] = "rp_rpointd_worker_set_busy";
	static char msg[] = "fatal error";
	static Err err;

	err = rp_mutex_lock(&((global.status_worker+id)->mutex));
	(global.status_worker+id)->state = SS_IDLE;
	err = rp_mutex_unlock(&((global.status_worker+id)->mutex));
	return err;
}

State rp_rpointd_worker_state(int id)
{
	static char fname[] = "rp_rpointd_worker_get_status";
	static char msg[] = "fatal error";
	static Err err;
	State state;

	err = rp_mutex_lock(&((global.status_worker+id)->mutex));
	state = (global.status_worker+id)->state;
	err = rp_mutex_unlock(&((global.status_worker+id)->mutex));

	return state;
}


